<template>
  <div>
    <div class="search">
      <SearchVue :searchType="searchType" @getSearchData="getSearchData"></SearchVue>
    </div>
    <div class="headeButton">
      <el-button type="primary" @click="addFn">添加内容</el-button>
    </div>
    <div class="draggable" style="padding: 20px">
      <el-table row-key="id" :data="tableData" style="width: 100%">
        <template v-for="(item, index) in oldList" :key="`col_${index}`">
          <el-table-column
            v-if="item.type == 1"
            :prop="newList[index].prop"
            :label="item.label"
            align="center"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            v-else-if="item.type == 2"
            :prop="newList[index].prop"
            :label="item.label"
            align="center"
          >
            <template #default="scope">
              <el-button type="warning" size="small" @click="changeTableFn(scope.row)"
                >修改</el-button
              >
              <el-popconfirm title="是否确认删除" @confirm="confirmDeleteFn(scope.row)">
                <template #reference>
                  <el-button type="danger" size="small"> 删除 </el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
          <el-table-column
            v-else-if="item.type == 3"
            :prop="newList[index].prop"
            :label="item.label"
            align="center"
          >
            <template #default="scope">
              <el-image style="width: 80px; height: 80px" :src="scope.row.image" />
            </template>
          </el-table-column>
        </template>
      </el-table>
      <el-pagination
        :current-page="pageData.page"
        :page-size="pageData.size"
        :page-sizes="[10, 20, 30, 40]"
        layout="total, sizes, prev, pager, next"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <el-dialog
      @close="closeFn"
      v-model="dialogVisibleAdd"
      title="添加"
      width="500"
      :before-close="dialogBeforeCloseFn"
    >
      <div>
        <el-form
          ref="formAddRef"
          :rules="rules"
          :model="formAdd"
          label-width="auto"
          style="max-width: 800px"
        >
          <el-form-item label="产品类型" prop="type">
            <el-select v-model="formAdd.type" class="imputeWidth" placeholder="请选择产品类型">
              <el-option
                v-for="item in optionsFilmType"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="产品型号" prop="name">
            <el-input v-model="formAdd.name" class="imputeWidth" placeholder="请输入产品型号" />
          </el-form-item>
          <el-form-item label="产品编号" prop="nameNumber">
            <el-input
              v-model="formAdd.nameNumber"
              class="imputeWidth"
              placeholder="请输入产品型号"
            />
          </el-form-item>
          <el-form-item label="质保年限" prop="age">
            <el-input v-model="formAdd.age" class="imputeWidth" placeholder="请输入质保年限" />
          </el-form-item>
          <el-form-item label="使用次数" prop="countAll">
            <el-input v-model="formAdd.countAll" class="imputeWidth" placeholder="请输入使用次数" />
          </el-form-item>
          <el-form-item label="漆面膜次数" prop="countAll">
            <el-input
              v-model="formAdd.lacquerNumber"
              class="imputeWidth"
              placeholder="请输入使用次数"
            />
          </el-form-item>
          <el-form-item label="改色膜次数" prop="countAll">
            <el-input
              v-model="formAdd.colorAlterationNumber"
              class="imputeWidth"
              placeholder="请输入使用次数"
            />
          </el-form-item>
          <el-form-item label="车顶膜次数" prop="countAll">
            <el-input
              v-model="formAdd.roofNumber"
              class="imputeWidth"
              placeholder="请输入使用次数"
            />
          </el-form-item>
          <el-form-item label="太阳膜次数" prop="countAll">
            <el-input
              v-model="formAdd.sunNumber"
              class="imputeWidth"
              placeholder="请输入使用次数"
            />
          </el-form-item>
          <el-form-item label="使用权限" prop="authority">
            <el-select v-model="formAdd.authority" class="imputeWidth" placeholder="请选择">
              <el-option label="公有" value="公有" />
              <el-option label="私有" value="私有" />
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="省份">
            <el-select
              @change="getstorelistAllFn"
              v-model="formAdd.province"
              placeholder="请选择性别"
              class="imputeWidth"
            >
              <el-option
                v-for="item in province"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item> -->
          <el-form-item label="可用门店" prop="usableStore">
            <el-select
              multiple
              v-model="formAdd.usableStore"
              placeholder="请选择门店"
              class="imputeWidth"
            >
              <el-option
                v-for="item in storeListAll"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer" style="display: flex; justify-content: center">
          <el-button type="primary" @click="confirmFn(0)"> 确定 </el-button>
          <el-button @click="confirmFn(1)">取消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="dialogVisibleImage">
      <div style="width: 100%; height: 100%">
        <img style="width: 100%; height: 100%" w-full :src="formAdd.image" alt="Preview Image" />
      </div>
    </el-dialog>
  </div>
</template>
 
<script setup >
import { getstorelistAll } from '@/http/api/store.js'
import { filmListAdd, filmList, filmListDelete, filmListChange, filmListSelect } from '@/http/api/film.js'
import Sortable from 'sortablejs'
import { onMounted, reactive, ref } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { baseURL } from '@/http/request.js'
import { ElMessage } from 'element-plus'
import { province } from '@/components/js/addressOptions'
import SearchVue from '@/components/search/index.vue'
// 只适合做平级的table行和列拖动
let optionsFilmType = [
  { value: '漆面膜', label: '漆面膜' },
  { value: '改色膜', label: '改色膜' },
  { value: '车顶膜', label: '车顶膜' },
  { value: '太阳膜', label: '太阳膜' }
]
let storeListAll = ref([])
let baseURL2 = baseURL
const oldList = ref()
const newList = ref()
// 表头
const tableItems = ref([
  {
    label: '产品类型',
    prop: 'type',
    type: 1
  },
  {
    label: '产品型号',
    prop: 'name',
    type: 1
  }, {
    label: '产品编号',
    prop: 'nameNumber',
    type: 1
  },
  {
    label: '质保年限',
    prop: 'age',
    type: 1
  }, {
    label: '使用次数',
    prop: 'countAll',
    type: 1
  }, {
    label: '漆面膜次数',
    prop: 'lacquerNumber',
    type: 1
  }, {
    label: '改色膜次数',
    prop: 'colorAlterationNumber',
    type: 1
  }, {
    label: '车顶膜次数',
    prop: 'roofNumber',
    type: 1
  }, {
    label: '太阳膜次数',
    prop: 'sunNumber',
    type: 1
  }, {
    label: '使用权限',
    prop: 'authority',
    type: 1
  }, {
    label: '可用门店',
    prop: 'usableStoreName',
    type: 1
  },
  {
    label: '操作',
    prop: 'age',
    type: 2
  },
])
let searchType = ref([
  {
    title: '产品类型：',
    type: 3,
    model: 'type',
    hint: '请选择',
    options: [
      {
        label: '漆面膜',
        value: '漆面膜'
      }, {
        label: '改色膜',
        value: '改色膜'
      }, {
        label: '车顶膜',
        value: '车顶膜'
      }, {
        label: '太阳膜',
        value: '太阳膜'
      },
    ]
  }, {
    title: '产品型号：',
    type: 1,
    model: 'name',
    hint: '请输入产品型号'
  }, {
    title: '质保年限：',
    type: 1,
    model: 'age',
    hint: '请输入质保年限'
  },
])
// 表体数据
let tableData = ref([])
let formAdd = reactive({})
let image = ref([])
let dialogVisibleImage = ref(false)
let pageData = reactive({
  page: 1,
  size: 10
})
const getData = async () => {
  const res = await filmList(pageData)
  tableData.value = res.data.res.map((item) => {
    item.usableStore = JSON.parse(item.usableStore)
    item.usableStoreName = JSON.parse(item.usableStoreName)
    return item
  })
  total.value = res.data.total
}
const getSearchData = async (data) => {
  let datas = {
    ...data,
    ...pageData
  }
  let res = await filmListSelect(datas)
  tableData.value = res.data.res.map((item) => {
    item.usableStore = JSON.parse(item.usableStore)
    item.usableStoreName = JSON.parse(item.usableStoreName)
    return {
      ...item,
    }
  })
  total.value = res.data.total
}
let dialogVisibleAdd = ref(false)
let total = ref(0)
const addFn = () => {
  dialogVisibleAdd.value = true
}
const closeFn = () => {
  dialogVisibleAdd.value = false
}

const rules = reactive({
  name: [
    { required: true, message: '请输入', trigger: 'blur' },
  ], nameNumber: [
    { required: true, message: '请输入', trigger: 'blur' },
  ],
  type: [
    { required: true, message: '请输入', trigger: 'blur' },
  ],
  age: [
    { required: true, message: '请输入', trigger: 'blur' },
  ],
  countAll: [
    { required: true, message: '请输入', trigger: 'blur' },
  ], authority: [
    { required: true, message: '请选择', trigger: 'blur' },
  ], usableStore: [
    { required: true, message: '请选择门店', trigger: 'blur' },
  ],

})
// 上传成功
const handSuccessFn = (data) => {
  formAdd.avatar = data.image_url
}
let formAddRef = ref()
// 点击添加或这修改按钮
const confirmFn = async (number) => {
  if (number == 0) {
    await formAddRef.value.validate(async (valid, fields) => {
      if (valid) {
        try {
          let numberAll = formAdd.lacquerNumber * 1 + formAdd.colorAlterationNumber * 1 + formAdd.roofNumber * 1 + formAdd.sunNumber * 1
          if (numberAll > formAdd.countAll || numberAll < formAdd.countAll) {
            throw '膜数量不等于总数量'
          }
          if (!formAdd.id) {
            formAdd.usableStoreName = []
            formAdd.usableStore.forEach((item) => {
              storeListAll.value.forEach((item2) => {
                if (item == item2.value) {
                  formAdd.usableStoreName.push(item2.label)
                }
              })
            })
            await filmListAdd(formAdd)
            ElMessage({
              message: '添加成功',
              type: 'success',
            })
          } else {
            await filmListChange(formAdd)
            ElMessage({
              message: '修改成功',
              type: 'success',
            })
          }
          getData()
          formAdd = reactive({})
          image.value = []
          dialogVisibleAdd.value = false
        } catch (error) {
          ElMessage({
            message: error,
            type: 'error',
          })
        }
      } else {
        ElMessage({
          message: '请补充完整信息',
          type: 'error',
        })
      }
    })
  }

}
// 关闭弹窗
const dialogBeforeCloseFn = () => {
  formAdd = reactive({})
  image.value = []
  dialogVisibleAdd.value = false
}
// 修改size
const handleSizeChange = (data) => {
  pageData.size = data
  getData()
}
// 修改页数
const handleCurrentChange = (data) => {
  pageData.page = data
  getData()
}
// 确定删除
const confirmDeleteFn = async (data) => {
  try {
    const res = await filmListDelete({ id: data.id })
    ElMessage({
      message: '删除成功',
      type: 'success',
    })
    getData()
  } catch (error) {
    ElMessage({
      message: '删除失败',
      type: 'error',
    })
  }

}
// 修改
const changeTableFn = (data) => {
  dialogVisibleAdd.value = true
  Object.assign(formAdd, data)
  console.log(formAdd)
  image.value = [{
    url: data.image,
    name: '11'
  }]
}
const handlePictureCardPreview = (data) => {
  dialogVisibleImage.value = true
}
// 根据省份获取门店
const getstorelistAllFn = async (data) => {
  const res = await getstorelistAll({ status: 1 })
  storeListAll.value = []
  storeListAll.value.push({
    value: 'all',
    label: '所有门店'
  })
  let storeLIst = res.data.res.map((item) => {
    return {
      label: item.name,
      value: item.id
    }
  })
  storeListAll.value.push(...storeLIst)
}
onMounted(() => {
  oldList.value = JSON.parse(JSON.stringify(tableItems.value))
  newList.value = JSON.parse(JSON.stringify(tableItems.value))
  getData()
  getstorelistAllFn()
})
</script>
<style lang="scss" scoped>
.imputeWidth {
  width: 260px;
}
</style>